<template>
  <VContainer>
    <VCard>
      <VToolbar color="primary" dark>
        <VToolbarTitle>初访预约审核</VToolbarTitle>
        <VSpacer />
        <VBtn icon @click="loadAppointments">
          <VIcon>mdi-refresh</VIcon>
        </VBtn>
      </VToolbar>
      
      <VCardText>
        <!-- 紧急预约部分 -->
        <VCard v-if="urgentAppointments.length > 0" class="mb-6" color="red-lighten-5">
          <VCardTitle class="bg-red-darken-1 text-white">
            <VIcon class="mr-2">mdi-alert</VIcon>
            紧急预约 ({{ urgentAppointments.length }}条)
          </VCardTitle>
          <VCardText>
            <VAlert type="error" class="mb-4">
              <VIcon>mdi-alert-circle</VIcon>
              以下学生的心理健康状况需要优先关注，请及时处理
            </VAlert>
            <VDataTable
              :headers="headers"
              :items="urgentAppointments"
              :loading="loading"
              class="elevation-1"
            >
              <template v-slot:item.student_name="{ item }">
                <VChip color="red" variant="outlined">
                  <VIcon start>mdi-account-alert</VIcon>
                  {{ item.student_name }}
                </VChip>
              </template>
              
              <template v-slot:item.is_urgent="{ item }">
                <VChip color="error" size="small">
                  <VIcon start>mdi-fire</VIcon>
                  紧急
                </VChip>
              </template>
              
              <template v-slot:item.apply_time="{ item }">
                {{ formatDateTime(item.apply_time) }}
              </template>
              
              <template v-slot:item.scheduled_time="{ item }">
                {{ formatDateTime(item.scheduled_time) }}
              </template>
              
              <template v-slot:item.student_info="{ item }">
                <div>
                  <div><strong>学号:</strong> {{ item.student_username || item.student_id }}</div>
                  <div><strong>电话:</strong> {{ item.student_phone || '未填写' }}</div>
                  <div><strong>院系:</strong> {{ item.student_department || '未知' }}</div>
                  <div><strong>班级:</strong> {{ item.student_class || '未知' }}</div>
                </div>
              </template>
              
              <template v-slot:item.actions="{ item }">
                <VBtn 
                  color="success" 
                  size="small" 
                  @click="approveAppointment(item.id, 'approve')"
                  class="mr-2"
                >
                  <VIcon start>mdi-check</VIcon>
                  通过
                </VBtn>
                <VBtn 
                  color="error" 
                  size="small" 
                  @click="approveAppointment(item.id, 'reject')"
                >
                  <VIcon start>mdi-close</VIcon>
                  拒绝
                </VBtn>
              </template>
            </VDataTable>
          </VCardText>
        </VCard>
        
        <!-- 普通预约部分 -->
        <VCard>
          <VCardTitle class="bg-blue-darken-1 text-white">
            <VIcon class="mr-2">mdi-calendar-clock</VIcon>
            普通预约 ({{ normalAppointments.length }}条)
          </VCardTitle>
          <VCardText>
            <VDataTable
              :headers="headers"
              :items="normalAppointments"
              :loading="loading"
              class="elevation-1"
            >
              <template v-slot:item.student_name="{ item }">
                <VChip color="blue" variant="outlined">
                  <VIcon start>mdi-account</VIcon>
                  {{ item.student_name }}
                </VChip>
              </template>
              
              <template v-slot:item.is_urgent="{ item }">
                <VChip color="info" size="small">
                  <VIcon start>mdi-clock</VIcon>
                  普通
                </VChip>
              </template>
              
              <template v-slot:item.apply_time="{ item }">
                {{ formatDateTime(item.apply_time) }}
              </template>
              
              <template v-slot:item.scheduled_time="{ item }">
                {{ formatDateTime(item.scheduled_time) }}
              </template>
              
              <template v-slot:item.student_info="{ item }">
                <div>
                  <div><strong>学号:</strong> {{ item.student_username || item.student_id }}</div>
                  <div><strong>电话:</strong> {{ item.student_phone || '未填写' }}</div>
                  <div><strong>院系:</strong> {{ item.student_department || '未知' }}</div>
                  <div><strong>班级:</strong> {{ item.student_class || '未知' }}</div>
                </div>
              </template>
              
              <template v-slot:item.actions="{ item }">
                <VBtn 
                  color="warning" 
                  size="small" 
                  @click="setPriority(item.id)"
                  class="mr-2"
                >
                  <VIcon start>mdi-arrow-up-bold</VIcon>
                  优先
                </VBtn>
                <VBtn 
                  color="success" 
                  size="small" 
                  @click="approveAppointment(item.id, 'approve')"
                  class="mr-2"
                >
                  <VIcon start>mdi-check</VIcon>
                  通过
                </VBtn>
                <VBtn 
                  color="error" 
                  size="small" 
                  @click="approveAppointment(item.id, 'reject')"
                >
                  <VIcon start>mdi-close</VIcon>
                  拒绝
                </VBtn>
              </template>
            </VDataTable>
          </VCardText>
        </VCard>
      </VCardText>
    </VCard>
  </VContainer>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useSnackbarStore } from '@/store/snackbarStore';
import axios from '@/plugins/axios';

const snackbarStore = useSnackbarStore();
const loading = ref(false);
const appointments = ref([]);

const headers = ref([
  { title: '学生姓名', key: 'student_name', sortable: false },
  { title: '紧急程度', key: 'is_urgent', sortable: false },
  { title: '申请时间', key: 'apply_time', sortable: true },
  { title: '预约时间', key: 'scheduled_time', sortable: false },
  { title: '预约地点', key: 'scheduled_place', sortable: false },
  { title: '学生信息', key: 'student_info', sortable: false },
  { title: '操作', key: 'actions', sortable: false }
]);

// 紧急预约
const urgentAppointments = computed(() => {
  return appointments.value.filter(app => app.is_urgent);
});

// 普通预约
const normalAppointments = computed(() => {
  return appointments.value.filter(app => !app.is_urgent);
});

const loadAppointments = async () => {
  loading.value = true;
  try {
    const { data } = await axios.get('/api/appointment/pending.do');
    if (data.success) {
      appointments.value = data.data;
      console.log('获取到的预约数据:', data.data);
      // 调试每条记录
      data.data.forEach((appointment, index) => {
        console.log(`预约${index + 1}:`, {
          id: appointment.id,
          student_id: appointment.student_id,
          student_name: appointment.student_name,
          student_username: appointment.student_username,
          is_urgent: appointment.is_urgent
        });
      });
    } else {
      snackbarStore.showMessage('获取预约列表失败');
    }
  } catch (error) {
    console.error('获取预约列表错误:', error);
    snackbarStore.showMessage('获取预约列表失败');
  } finally {
    loading.value = false;
  }
};

const approveAppointment = async (appointmentId: number, action: string) => {
  try {
    const { data } = await axios.post('/api/appointment/approve.do', {
      appointmentId: appointmentId,
      action: action,
      reviewerId: 1 // 临时使用管理员ID，实际应从登录状态获取
    });
    
    if (data.success) {
      snackbarStore.showMessage(data.message);
      loadAppointments(); // 重新加载数据
    } else {
      snackbarStore.showMessage('操作失败');
    }
  } catch (error) {
    snackbarStore.showMessage('操作失败');
  }
};

const setPriority = async (appointmentId: number) => {
  try {
    const { data } = await axios.post('/api/appointment/priority.do', {
      appointmentId: appointmentId
    });
    
    if (data.success) {
      snackbarStore.showMessage(data.message);
      loadAppointments(); // 重新加载数据
    } else {
      snackbarStore.showMessage('设置优先排队失败');
    }
  } catch (error) {
    snackbarStore.showMessage('设置优先排队失败');
  }
};

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '';
  return new Date(dateTime).toLocaleString('zh-CN');
};

onMounted(() => {
  loadAppointments();
});
</script>

<style scoped>
.v-card {
  margin-bottom: 20px;
}

.v-chip {
  margin: 2px;
}

.elevation-1 {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style> 